#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

/* receive webpage data */
size_t receive_data(void *buffer, size_t size, size_t nmemb, void *userp){
	FILE *fptr = (FILE *)userp;
	fwrite(buffer, size, nmemb, fptr);
	return nmemb;
}

int main(int argc, char *argv[]) {
	struct timeval tv1, tv2;
	CURL *curl;
	CURLcode res;
	char envbuff[32];
	int isPrintWeb = 0, isPrintLog = 0;
	FILE *fp;
	char FILENAME[261];

	if(argc < 2 || argc > 4){
        	printf("Usage: TestWebtime url [printWeb?][printLog?]\n");
        	return 1;
	}
	if(argc >= 3)
		isPrintWeb = atoi(argv[2]);
	if(argc == 4)
		isPrintLog = atoi(argv[3]);

   	curl_global_init(CURL_GLOBAL_ALL);
	curl = curl_easy_init();

	curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
	if(!isPrintWeb){
		strcpy(FILENAME, argv[1]);
		strcat(FILENAME, ".html");
		if((fp = fopen(FILENAME, "w")) == NULL){
			fprintf(stderr, "fopen file error: %s\n", FILENAME);
			exit(1);
		}
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
	}
	if(isPrintLog)
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); //print out the log information

	gettimeofday(&tv1, NULL);
	res = curl_easy_perform(curl);
	gettimeofday(&tv2, NULL);
	curl_easy_cleanup(curl);
	if(!isPrintWeb)
		fclose(fp);
	else	printf("\n");
	if(res == CURLE_OK){
		int delsec = tv2.tv_sec - tv1.tv_sec;
		int delmsec = (delsec * 1000000 + tv2.tv_usec - tv1.tv_usec) / 1000;
		sprintf(envbuff, "%d", delmsec);
		setenv("res", envbuff, 1);
		printf("used time : %s(ms)\n", getenv("res"));
		return delmsec;
    	}else{
       		//printf("\nError!\n");
		return 0;
    	}

}
